package com.mane.controller;

import com.mane.Util.JwtUtil;
import com.mane.entity.DTO.LoginDTO;
import com.mane.entity.Result;
import com.mane.entity.VO.RouterVo;
import com.mane.interceptor.AuthenticationContextHolder;
import com.mane.pojo.Menu;
import com.mane.pojo.User;
import com.mane.service.IMenuService;
import com.mane.service.IUserService;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.TimeUnit;

import static com.mane.entity.Result.ok;

@RestController
@RequestMapping("/system")
public class LoginController {
    @Autowired
    private IUserService userService;
    @Autowired
    private IMenuService menuService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/login")
    public Result<Map<String,Object>> login(@RequestBody LoginDTO loginDTO) {

        User user = userService.login(loginDTO);
        // 判断登录的结果
        if(user == null){
            return Result.error("用户名或者密码错误");
        }
        if(user.getIsDisabled().equals("1")){
            return Result.error("该账号已经被禁用");
        }
        //使用JWT生成token
        Map<String,Object> map = new HashMap<>();
        map.put("username",user.getUsername());
        String token = JwtUtil.createJWT(UUID.randomUUID().toString(), map, 1000 * 60 * 60 * 30L);

        //将token保存在redis里面
        stringRedisTemplate.opsForValue().set("token-"+user.getUsername(), token, 60 * 60 * 30L, TimeUnit.SECONDS);

        //将token发送给前端页面
        Map<String,Object> mapResult = new HashMap<>();
        mapResult.put("token",token);
        return ok(mapResult) ;
    }

    @GetMapping("/info")
    @Operation(summary = "获取登录用户信息")
    public Result<Map<String, Object>> info(HttpServletRequest request) throws Exception {
        // 1. 从请求头中获取token，此时token就是用户名
//        String token = request.getHeader("Authorization");
//        if(!StringUtils.hasLength(token) || !token.startsWith("Bearer ")){
//            return Result.error("非法的token");
//        }
//        //1.1解密token
//        token = token.substring(7);
//        Claims claims = JwtUtil.parseJWT(token);
//        String username = claims.get("username").toString();
        String username = AuthenticationContextHolder.getContext();
        // 2. 根据token获取用户的信息
        User user = userService.selectUserByUsername(username);
        // 3. 根据token获取角色信息
        List<String> roles = new ArrayList<>();
        roles.add("admin");
        // 4. 根据token获取权限信息
        List<String> permissions = new ArrayList<>();
        permissions.add("*:*:*");
        // 5. 返回数据
        Map<String, Object> map = new HashMap<>();
        map.put("user", user);
        map.put("roles", roles);
        map.put("permissions", permissions);
        return Result.ok(map);
    }

    @GetMapping("/router")
    public Result<List<RouterVo>> listRouterMenus(HttpServletRequest request) throws Exception {
//        String Authorization = request.getHeader("Authorization");
//        if(StringUtils.isEmpty(Authorization) || !Authorization.startsWith("Bearer ")){
//            return Result.error("非法的token");
//        }
//        String token = Authorization.substring(7);
//        Claims claims = JwtUtil.parseJWT(token);
//        String username = claims.get("username").toString();
        String username = AuthenticationContextHolder.getContext();
        // 根据用户名获取该用户具备的权限菜单列表
        List<Menu> menus = menuService.listTreeMenusByUsername(username);
        List<RouterVo> routerVos = menuService.buildMenus(menus);
        return Result.ok(routerVos);
    }
    @PostMapping("/loginOut")
    public Result logout(HttpServletRequest request) {
        return Result.ok("注销成功");
    }
}
